#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/7/29 14:59
# @Author  : 王凯
# @File    : app_fav.py
# @Project : scrapy_spider
import concurrent.futures
import random
import time

import requests
from loguru import logger

from apps.pdd.pdd.utils.app.core.pdd_user import PDDAppUserPool
from components.config import WFQ_SOURCE_MYSQL_CONFIG
from utils.db.mysqldb import MysqlDB
from utils.proxies_tools import get_company_ip_crawler_by_api


class AppFav(object):

    def __init__(self, user, auto_next=False):
        self.session = requests.Session()
        self.session.headers = user["headers"]
        self.session.cookies.update(user["cookies"])
        if "proxies" in user:
            self.session.proxies = user["proxies"]
        else:
            self.session.proxies = get_company_ip_crawler_by_api(static=True)
        self._to_db = None
        self.auto_next = auto_next

    @property
    def to_db(self):
        if self._to_db is None:
            self._to_db = MysqlDB(
                ip=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_IP"],
                port=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_PORT"],
                db=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_DB"],
                user_name=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_USER_NAME"],
                user_pass=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_USER_PASS"],
            )
        return self._to_db

    def like_mall(self, mall_id):
        time.sleep(random.randint(30, 60))
        res = self.session.get(f"https://api.pinduoduo.com/favorite/mall/like/{mall_id}").json()
        logger.info(
            "like(user【{}】) mall: {} ,  res: {}".format(
                self.session.cookies.get("pdd_user_id", default=""), mall_id, res
            )
        )
        if res.get("error_code"):
            raise Exception(res)
        if res.get("server_time") == 0:
            raise Exception(res)

    def gen_anti_content(self, timestamp=int(time.time() * 1000), device_id=None):
        response = requests.post(
            "http://api.wkaanig.cn/unidbg-server/unidbg/pddSecretToken",
            data={"timestamp": timestamp, "deviceId": device_id or ""},
        ).json()
        logger.debug(f"获取 anti_count : {response}")
        rt = response["data"]
        return rt

    def like_mall_by_api(self, mall_id):
        """
        res: {'success': False, 'error_code': 74002, 'error_msg': '风控校验不通过'}
        """
        url = "https://api-shb1.pinduoduo.com/api/hanfeizi/publisher/follow"
        params = {"pdduid": self.session.cookies.get("pdd_user_id", default="")}
        data = {
            "publisher_id": f"{mall_id}",
            "publisher_type": "2",
            "page_sn": "10039",
            "like_from": "100101",
            "page_el_sn": "99796",
        }
        headers = {
            **self.session.headers,
            "anti-token": self.gen_anti_content(),
        }
        res = self.session.post(url, params=params, data=data, headers=headers).json()
        logger.info(
            "like(user【{}】) mall: {} ,  res: {}".format(
                self.session.cookies.get("pdd_user_id", default=""), mall_id, res
            )
        )
        if not res.get("success"):
            raise Exception(res)

    def get_fav_list(self, page=1):
        res = self.session.get(f"https://api.pinduoduo.com/favorite/mall/list?page={page}").json()
        logger.info("page: {}, res: {}".format(page, res))
        if res.get("error_code"):
            raise Exception(res)
        return res

    def get_fav_list_by_api(self, page=1):
        url = "https://api.pinduoduo.com/api/light/mall/fav/integration/render"
        params = {"pdduid": self.session.cookies.get("pdd_user_id", default="")}
        data = {
            "fav_page_version": "3",
            "_light_show_often_visit": "1",
            "source_type": 1,
            "page_source": 0,
            "page_no": page,
            "page_size": 10,
        }
        headers = {
            **self.session.headers,
            "anti-token": self.gen_anti_content(),
        }
        res = self.session.post(url, params=params, data=data, headers=headers).json()
        logger.info("page: {}, res: {}".format(page, res))
        if res.get("error_code"):
            raise Exception(res)
        return res

    def parse_data(self, response):
        """
        {"mall_list": [{"logo": "http://t16img.yangkeduo.com/pdd_ims/img_check/v2/FFF0E6E6882C0120200112155259495/0a256d43a6b34aa8bf03aa093ecc96a7.png", "is_open": 1, "mall_id": 136890254, "mall_name": "三泰百货商行", "brand_name": "三泰百货商行", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=136890254&msn=zsttqscsn6zarq3mbuv6fxture_axbuy&_sop_rcto=YWJWUnSPfxhEM-5eQAIb4Ufx", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [], "mall_goods_num": 12, "mall_coupon_available": 0}, {"logo": "http://t16img.yangkeduo.com/pdd_ims/15fc77c3608d291f5e4325f98fe39d7e.jpg", "is_open": 1, "mall_id": 1283012, "mall_name": "保护伞酒品批发", "brand_name": "保护伞酒品批发", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=1283012&msn=hfeslyrtiq5cpdypqfwaknuvda_axbuy&_sop_rcto=YWKSQ2JBItDfZkZcl978JPak", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [{"url": "https://promotion.pddpic.com/oms-img-promotion/2024-12-15/851c675c-d0bc-4c55-b799-77172b59d9de.png", "width": 168, "height": 48, "icon_type": 4}], "mall_goods_num": 49, "mall_coupon_available": 0}, {"logo": "https://img.pddpic.com/goods_mms/2024-04-25/b1fe789f-6f6d-48df-b671-d68a5fcbe50f_suffix.jpeg", "is_open": 1, "mall_id": 127691522, "mall_name": "精美礼品工厂", "brand_name": "精美礼品工厂", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=127691522&msn=meqctnuwevgpgbedigmqr7l4e4_axbuy&_sop_rcto=YWI-c61zSwUbmSg58cL1D6J1", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [], "mall_goods_num": 9, "mall_coupon_available": 0}, {"logo": "http://t16img.yangkeduo.com/pdd_ims/img_check/v2/E62F2CFFFFFF0720200112154059921/64f05cb4f53945b7b23468d0a222f6ba.png", "is_open": 1, "mall_id": 126023667, "mall_name": "芒果小猪", "brand_name": "芒果小猪", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=126023667&msn=vvzjdgocospa7tpuicmwgn3rfi_axbuy&_sop_rcto=YWKn8Ad_SU0kU_a1G77Cwzpz&has_decoration=1", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [], "mall_goods_num": 121, "mall_coupon_available": 0}, {"logo": "https://img.pddpic.com/goods_mms/2024-12-26/f2edee14-10c8-4727-9258-b31132071097.jpeg.a.jpeg", "is_open": 1, "mall_id": 125966482, "mall_name": "花喜子", "brand_name": "花喜子", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=125966482&msn=ej2apqv75bpf7zcdj47xlnjycm_axbuy&_sop_rcto=YWI0Pt1GQEU2FMqbOffDQVfc", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [], "mall_goods_num": 5, "mall_coupon_available": 0}, {"logo": "http://t00img.yangkeduo.com/goods/images/2019-02-13/8beb68a6-63b5-4ced-b6b8-fe4368f0bc6a.jpg", "is_open": 1, "mall_id": 1198045, "mall_name": "河北奥诺体育", "brand_name": "河北奥诺体育", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=1198045&msn=zlnblnnwi4v7mruzsk2n5gyjpm_axbuy&_sop_rcto=YWIbFSURXi3njvCrt6Ptv0um&has_decoration=1", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [], "mall_goods_num": 15, "mall_coupon_available": 0}, {"logo": "http://t16img.yangkeduo.com/pdd_ims/mainObject/v1/pub_202206178fc2e099193647369528ccffca652055.jpg", "is_open": 1, "mall_id": 1178672, "mall_name": "久久游", "brand_name": "久久游", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=1178672&msn=ahqzxhj4b44nyy4aynnlkqkiey_axbuy&_sop_rcto=YWL_A8R1HTwgZPt-6Tpry2CP", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [], "mall_goods_num": 5, "mall_coupon_available": 0}, {"logo": "http://t16img.yangkeduo.com/pdd_ims/2020-12-05/63035631-a981-4979-969f-4ae86a178899.jpeg", "is_open": 1, "mall_id": 112421796, "mall_name": "晨洁家居生活馆", "brand_name": "晨洁家居生活馆", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=112421796&msn=grsxzluii5em4derz2per2ogzu_axbuy&_sop_rcto=YWLgGz05okmKrNSMv3sIchkH&has_decoration=1", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [{"url": "https://promotion.pddpic.com/oms-img-promotion/2024-12-15/851c675c-d0bc-4c55-b799-77172b59d9de.png", "width": 168, "height": 48, "icon_type": 4}], "mall_goods_num": 226, "mall_coupon_available": 0}, {"logo": "https://img.pddpic.com/goods_mms/2024-07-17/ce11e90b-cf26-4cde-84f5-405aaf838c14_suffix.jpeg", "is_open": 1, "mall_id": 101457548, "mall_name": "坦博尔童装官方旗舰店", "brand_name": "坦博尔童装官方旗舰店", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=101457548&msn=mdptuew5rdzom5xr3blxbe7zrq_axbuy&_sop_rcto=YWKyp0act8s8SRn5Lvf0Uohk&has_decoration=1", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [{"url": "https://funimg.pddpic.com/d66b3a03-0041-482b-82c7-ab9d5f9f1603.png", "width": 90, "height": 48, "icon_type": 1}, {"url": "https://promotion.pddpic.com/oms-img-promotion/2024-12-15/851c675c-d0bc-4c55-b799-77172b59d9de.png", "width": 168, "height": 48, "icon_type": 4}], "mall_goods_num": 51, "mall_coupon_available": 0}, {"logo": "https://t00img.yangkeduo.com/goods/images/2020-10-26/3af6045b-03f8-49f6-8084-5ac4204bf625_suffix.jpeg", "is_open": 1, "mall_id": 210584197, "mall_name": "乔乐乐食品店", "brand_name": "乔乐乐食品店", "mall_sales": 0, "router_info": {"pdd_router": "mall_page.html?mall_id=210584197&msn=3fb2al7wzajnn6tjr33ll6uxxi_axbuy&_sop_rcto=YWIzEO-p8YBhJexoXWfyJPQ3&has_decoration=1", "pdd_router_name": "进店逛逛"}, "mall_icon_bos": [], "mall_goods_num": 10, "mall_coupon_available": 0}], "server_time": 1735613254, "favorite_mall_update_time": 1735287499}
        """
        datas = response.get("mall_list", [])
        result = []
        for data in datas:
            mall_id = data["mall_id"]
            shop_name = data["mall_name"]
            is_open = data["is_open"]
            mall_goods_num = data["mall_goods_num"]
            mall_sales = data["mall_sales"]
            pdd_route = data["router_info"]["pdd_router"]
            params = dict([i.split("=") for i in pdd_route.split("?")[1].split("&")])
            item = {
                "mall_id": mall_id,
                "shop_name": shop_name,
                "msn": params.get("msn"),
                "_sop_rcto": params.get("_sop_rcto"),
                "mall_goods_num": mall_goods_num,
                "mall_sales": mall_sales,
            }
            # if is_open == 0 and mall_goods_num == 0 and mall_sales == 0:
            #     item["flag"] = -1
            #     item["shop_status"] = "该店铺已失效"
            result.append(item)
        return result

    def save_datas(self, datas):
        with concurrent.futures.ThreadPoolExecutor(max_workers=10) as e:
            for i in datas:
                e.submit(
                    self.to_db.update_smart,
                    "net_pdd_shop_info",
                    i,
                    condition=f"mall_id='{i['mall_id']}'",
                )

    def run(self):
        page = 1
        response = self.get_fav_list(page=page)
        datas = response.get("mall_list")
        if len(datas) < 20:
            has_more = False
        else:
            has_more = True
        self.save_datas(self.parse_data(response))
        if self.auto_next:
            while has_more is True:
                page += 1
                response = self.get_fav_list(page=page)
                datas = response.get("mall_list")
                if len(datas) < 20:
                    has_more = False
                self.save_datas(self.parse_data(response))

    def run_by_api(self):
        page = 1
        response = self.get_fav_list_by_api(page=page)
        has_more = response.get("fav_mall_list", {}).get("has_more")
        self.save_datas(self.parse_data_by_api(response))
        if self.auto_next:
            while has_more is True:
                page += 1
                response = self.get_fav_list_by_api(page=page)
                has_more = response.get("fav_mall_list", {}).get("has_more")
                self.save_datas(self.parse_data_by_api(response))

    def parse_data_by_api(self, response):
        """
        {"fav_mall_list":{"section_title":"全部关注","section_no_data_content":"暂无关注的店铺","section_no_more_data_content":"已显示全部","list":[{"view_element_type":15,"publisher_id":"896229","source_publisher_id":896229,"publisher_type":2,"publisher_name":"宇盛堂","publisher_character_desc":"已拼40万+件","publisher_link":"mall_page.html?mall_id=896229&msn=vqqlyuarrwvf5ylmjd74ssu6lu_axbuy&_sop_rcto=YWKqI68zmgI3225jDf7uU4JRTuXTx_3fIjo&mall_info=%7B%22mall_name%22%3A%22%5Cu5B87%5Cu76DB%5Cu5802%22%2C%22mall_logo%22%3A%22http%3A%2F%2Ft16img.yangkeduo.com%2Fpdd_ims%2Fdce58007e2f5f081c729696456f86672.jpg%22%2C%22sales_tip%22%3A%22%5Cu5DF2%5Cu62FC40%5Cu4E07%2B%5Cu4EF6%22%2C%22favorite_tips%22%3A%225049%5Cu4EBA%5Cu5173%5Cu6CE8%22%2C%22is_favorite%22%3A1%2C%22is_tag%22%3A1%2C%22is_mall_name_label%22%3A0%2C%22in_new_favorite_icon_gray%22%3A1%7D&mall_tab_key=home_page&focus_content=0&tab_type=0","logo":"http://t16img.yangkeduo.com/pdd_ims/dce58007e2f5f081c729696456f86672.jpg","is_open":1,"pdd_route":"mall_page.html?mall_id=896229&msn=vqqlyuarrwvf5ylmjd74ssu6lu_axbuy&_sop_rcto=YWKqI68zmgI3225jDf7uU4JRTuXTx_3fIjo&mall_info=%7B%22mall_name%22%3A%22%5Cu5B87%5Cu76DB%5Cu5802%22%2C%22mall_logo%22%3A%22http%3A%2F%2Ft16img.yangkeduo.com%2Fpdd_ims%2Fdce58007e2f5f081c729696456f86672.jpg%22%2C%22sales_tip%22%3A%22%5Cu5DF2%5Cu62FC40%5Cu4E07%2B%5Cu4EF6%22%2C%22favorite_tips%22%3A%225049%5Cu4EBA%5Cu5173%5Cu6CE8%22%2C%22is_favorite%22%3A1%2C%22is_tag%22%3A1%2C%22is_mall_name_label%22%3A0%2C%22in_new_favorite_icon_gray%22%3A1%7D","is_show_follow_icon":0,"sub_title_tag_list":[{"text":"满58减2","color":"#FFE02E24"}],"pdd_route_name":"进店逛逛","mall_show_type":0,"tag_list":[],"mall_id":896229,"mall_name":"宇盛堂","sales_tip":"已拼: 40万+件","mall_link":"mall_page.html?mall_id=896229&msn=vqqlyuarrwvf5ylmjd74ssu6lu_axbuy&_sop_rcto=YWKqI68zmgI3225jDf7uU4JRTuXTx_3fIjo&mall_info=%7B%22mall_name%22%3A%22%5Cu5B87%5Cu76DB%5Cu5802%22%2C%22mall_logo%22%3A%22http%3A%2F%2Ft16img.yangkeduo.com%2Fpdd_ims%2Fdce58007e2f5f081c729696456f86672.jpg%22%2C%22sales_tip%22%3A%22%5Cu5DF2%5Cu62FC40%5Cu4E07%2B%5Cu4EF6%22%2C%22favorite_tips%22%3A%225049%5Cu4EBA%5Cu5173%5Cu6CE8%22%2C%22is_favorite%22%3A1%2C%22is_tag%22%3A1%2C%22is_mall_name_label%22%3A0%2C%22in_new_favorite_icon_gray%22%3A1%7D&mall_tab_key=home_page&focus_content=0&tab_type=0","goods_list":[{"view_element_type":2,"goods_id":285130647708,"goods_name":"苦丁茶新茶批发正宗小叶苦丁茶叶青山绿水茶余庆小叶苦丁散装灌装","goods_url":"goods.html?goods_id=285130647708&_oak_rcto=YWKn0gtn_ZceEDZI3IOy-aiM6_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://img.pddpic.com/gaudit-image/2021-11-10/1bd97477d9f4fc52164c9cebbf7f4962.jpeg","hd_url":"https://img.pddpic.com/mms-material-img/2021-11-09/e7fbc2ee-4cd3-4840-877f-dae0cf63f526.jpeg.a.jpeg","sold_quantity":0,"price":308},{"view_element_type":2,"goods_id":528775084569,"goods_name":"番泻叶正品天然泻叶番泻叶散装蕃泻叶潘泄叶500g10g","goods_url":"goods.html?goods_id=528775084569&_oak_rcto=YWI-lRR_50LnEg87kpmnXI6X6_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://img.pddpic.com/gaudit-image/2023-09-21/6705d1a45b925a1b02e5eb0a8146a15a.jpeg","hd_url":"https://img.pddpic.com/mms-material-img/2023-09-21/27acc492-d6bf-4502-b6e6-3bd06007186c.jpeg","sold_quantity":0,"price":156},{"view_element_type":2,"goods_id":236879131582,"goods_name":"玉米须茶纯干玉米须泡水新鲜天然苞米棒子胡须龙须茶玉米须子批发","goods_url":"goods.html?goods_id=236879131582&_oak_rcto=YWIwdoOMQiIEFgY8am-v4MIj6_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://t00img.yangkeduo.com/goods/images/2021-04-20/c28b0bc76429b91f3857d6b801750d0a.jpeg","hd_url":"https://img.pddpic.com/mms-material-img/2021-04-20/a9b0968d-e30c-41aa-8086-509086fe2a22.jpeg.a.jpeg","sold_quantity":0,"price":215},{"view_element_type":2,"goods_id":437526076740,"goods_name":"干冬瓜皮晒干冬瓜皮片泡茶新鲜冬瓜荷叶茶包冬瓜茶散装冬瓜皮批发","goods_url":"goods.html?goods_id=437526076740&_oak_rcto=YWL9YlUgCdlWIciUe0AecZtG6_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://img.pddpic.com/gaudit-image/2022-12-05/29989daaa0d7f3ded91c161860d1b8fd.jpeg","hd_url":"https://t00img.yangkeduo.com/goods/images/2020-05-13/ecc6f7b1e90af837795a6498d9ab8027.jpeg","sold_quantity":0,"price":325},{"view_element_type":2,"goods_id":528788966170,"goods_name":"泡水喝胡须正宗玉米须茶正品纯干玉米须须子天然散装农家苞米须","goods_url":"goods.html?goods_id=528788966170&_oak_rcto=YWIULsyimPbvIsd51LnYTGRU6_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://img.pddpic.com/gaudit-image/2023-12-28/2b33d89df98f907e276ff47b745b248c.jpeg","hd_url":"https://img.pddpic.com/mms-material-img/2023-09-21/e332df2e-b21d-4da1-89a8-018bd6a6945a.jpeg","sold_quantity":0,"price":216},{"view_element_type":2,"goods_id":139805819520,"goods_name":"蒲公英茶天然野生蒲公英泡水喝正宗长白山蒲公英根茶叶婆婆丁泡茶","goods_url":"goods.html?goods_id=139805819520&_oak_rcto=YWIhFXEvA5ATJalh78Qek1nN6_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://img.pddpic.com/gaudit-image/2023-08-09/80de5a16187cba9a1aee350b6a2693e1.jpeg","hd_url":"https://img.pddpic.com/mms-material-img/2021-08-30/a5fdeeb2-c2c2-4f4e-b361-9639d71a9674.jpeg.a.jpeg","sold_quantity":0,"price":351},{"view_element_type":2,"goods_id":338741509993,"goods_name":"白茅根野生正宗茅根干茅草根野生白毛根批发干货茅根新鲜甜草根","goods_url":"goods.html?goods_id=338741509993&_oak_rcto=YWLhV9FTy0X7U39r4VaW33fV6_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://img.pddpic.com/gaudit-image/2023-12-29/e591e8303bb45468c30da75a7581612b.jpeg","hd_url":"https://img.pddpic.com/mms-material-img/2023-12-29/17be3b1b-2c3e-4ef0-8036-fa0ef52549db.jpeg","sold_quantity":0,"price":560},{"view_element_type":2,"goods_id":434048651403,"goods_name":"蒲公英正宗长白山蒲公英根茶蒲公英叶子蒲公英泡水喝野生婆婆丁","goods_url":"goods.html?goods_id=434048651403&_oak_rcto=YWKb4n5O1UjW0lD9cvwyTxml6_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://img.pddpic.com/gaudit-image/2022-11-23/f293130abe44822d1c16c487f3014ce4.jpeg","hd_url":"https://img.pddpic.com/mms-material-img/2021-08-30/a5fdeeb2-c2c2-4f4e-b361-9639d71a9674.jpeg.a.jpeg","sold_quantity":0,"price":281},{"view_element_type":2,"goods_id":112512628107,"goods_name":"荷叶茶微山湖干荷叶包邮荷叶片散装荷叶块冬瓜荷叶茶批发干荷叶","goods_url":"goods.html?goods_id=112512628107&_oak_rcto=YWKGHiwF2j_1rwkeg-iJdTlJ6_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://img.pddpic.com/gaudit-image/2022-04-13/54c69a13f7ad2a95fa6c0de671441bae.jpeg","hd_url":"https://img.pddpic.com/mms-material-img/2022-04-13/07f2da94-9f1a-40ae-8fe3-2cc300faaab8.jpeg.a.jpeg","sold_quantity":0,"price":207},{"view_element_type":2,"goods_id":114127880701,"goods_name":"野菊花胎菊批发包邮新鲜野菊米小胎菊花小米菊苦菊散装袋装菊花茶","goods_url":"goods.html?goods_id=114127880701&_oak_rcto=YWJdjKuukmt3znR2AewJLDS26_6BBXUF9NKYUDjBkmkvOIvFSg0TqAI4&_oc_refer_ad=0","thumb_url":"https://t00img.yangkeduo.com/goods/images/2020-04-28/84e95fb25928eef9999268f7ddace674.jpeg","hd_url":"https://t00img.yangkeduo.com/goods/images/2020-04-28/524797ca-005a-416a-9867-b61534761c40.jpg","sold_quantity":0,"price":573}],"cate_list":[-1,10012]}],"has_more":false,"cate_list":[{"cate_id":-1,"cate_name":"全部关注","cate_count":1},{"cate_id":10012,"cate_name":"食品","cate_count":1}],"cur_cate_count":1,"merchant_tag":41047},"often_visit_entrance":{"section_title":"最近常逛","list":[{"view_element_type":7,"publisher_id":"896229","source_publisher_id":896229,"publisher_type":2,"publisher_name":"宇盛堂","publisher_link":"mall_page.html?mall_id=896229&msn=vqqlyuarrwvf5ylmjd74ssu6lu_axbuy&_sop_rcto=YWKqI68zmgI3225jDf7uU4JRTuXTx_3fIjo&mall_info=%7B%22mall_name%22%3A%22%5Cu5B87%5Cu76DB%5Cu5802%22%2C%22mall_logo%22%3A%22http%3A%2F%2Ft16img.yangkeduo.com%2Fpdd_ims%2Fdce58007e2f5f081c729696456f86672.jpg%22%2C%22sales_tip%22%3A%22%5Cu5DF2%5Cu62FC40%5Cu4E07%2B%5Cu4EF6%22%2C%22favorite_tips%22%3A%225049%5Cu4EBA%5Cu5173%5Cu6CE8%22%2C%22is_favorite%22%3A1%2C%22is_tag%22%3A1%2C%22is_mall_name_label%22%3A0%2C%22in_new_favorite_icon_gray%22%3A1%7D&mall_tab_key=home_page&focus_content=0&tab_type=0","logo":"http://t16img.yangkeduo.com/pdd_ims/dce58007e2f5f081c729696456f86672.jpg","is_open":1,"pdd_route":"mall_page.html?mall_id=896229&msn=vqqlyuarrwvf5ylmjd74ssu6lu_axbuy&_sop_rcto=YWKqI68zmgI3225jDf7uU4JRTuXTx_3fIjo&mall_info=%7B%22mall_name%22%3A%22%5Cu5B87%5Cu76DB%5Cu5802%22%2C%22mall_logo%22%3A%22http%3A%2F%2Ft16img.yangkeduo.com%2Fpdd_ims%2Fdce58007e2f5f081c729696456f86672.jpg%22%2C%22sales_tip%22%3A%22%5Cu5DF2%5Cu62FC40%5Cu4E07%2B%5Cu4EF6%22%2C%22favorite_tips%22%3A%225049%5Cu4EBA%5Cu5173%5Cu6CE8%22%2C%22is_favorite%22%3A1%2C%22is_tag%22%3A1%2C%22is_mall_name_label%22%3A0%2C%22in_new_favorite_icon_gray%22%3A1%7D","is_show_follow_icon":0,"p_rec":{},"goods_num_tip":"商品:158","mall_show_type":0,"mall_id":896229,"mall_name":"宇盛堂","mall_link":"mall_page.html?mall_id=896229&msn=vqqlyuarrwvf5ylmjd74ssu6lu_axbuy&_sop_rcto=YWKqI68zmgI3225jDf7uU4JRTuXTx_3fIjo&mall_info=%7B%22mall_name%22%3A%22%5Cu5B87%5Cu76DB%5Cu5802%22%2C%22mall_logo%22%3A%22http%3A%2F%2Ft16img.yangkeduo.com%2Fpdd_ims%2Fdce58007e2f5f081c729696456f86672.jpg%22%2C%22sales_tip%22%3A%22%5Cu5DF2%5Cu62FC40%5Cu4E07%2B%5Cu4EF6%22%2C%22favorite_tips%22%3A%225049%5Cu4EBA%5Cu5173%5Cu6CE8%22%2C%22is_favorite%22%3A1%2C%22is_tag%22%3A1%2C%22is_mall_name_label%22%3A0%2C%22in_new_favorite_icon_gray%22%3A1%7D&mall_tab_key=home_page&focus_content=0&tab_type=0","is_on_live":0}],"has_more":false},"server_time":1739889424}
        """
        datas = response.get("mall_list", [])
        result = []
        for data in datas:
            mall_id = data["mall_id"]
            shop_name = data["mall_name"]
            is_open = data["is_open"]
            logo = data["logo"]
            mall_goods_num = data.get("mall_goods_num")  # 无
            mall_sales = data.get("mall_sales")  # 无
            pdd_route = data["mall_link"]
            params = dict([i.split("=") for i in pdd_route.split("?")[1].split("&")])
            item = {
                "mall_id": mall_id,
                "shop_name": shop_name,
                "msn": params.get("msn"),
                "_sop_rcto": params.get("_sop_rcto"),
                "mall_goods_num": mall_goods_num,
                "logo": logo,
                "mall_sales": mall_sales,
            }
            if is_open == 0:
                item["flag"] = -1
                item["shop_status"] = "该店铺已失效"
            result.append(item)
        return result

    def get_mall_ids(self):
        sql = "select mall_id from net_pdd_shop_info where msn is null limit 1000"
        result = self.to_db.find(sql, to_json=True)
        if result:
            mall_ids = [i["mall_id"] for i in result]
            mall_ids = random.choices(mall_ids, k=10)
            return mall_ids
        return []

    def run_forever(self):
        while True:
            self.run_one()
            time.sleep(60 * 60 + random.randint(5, 20) * 60)

    def run_one(self, user=None):
        try:
            sub_mall_ids = self.get_mall_ids()
            for mall_id in sub_mall_ids:
                try:
                    self.like_mall(mall_id=mall_id)
                    # self.like_mall_by_api(mall_id=mall_id)
                except Exception as e:
                    self.run()
                    raise e
            self.run()
        except Exception as e:
            logger.error(e)
            if "40001" in str(e):
                if user:
                    user.refresh()

    def auto_run(self):
        pass


def run():
    while True:
        user = PDDAppUserPool(redis_key="user:pdd:app", max_users_num=10, keep_alive=True).get_user()
        logger.info("user: 【{}】：{}".format(user.username, user.user_id))
        AppFav({"headers": user.headers, "cookies": user.cookies}).run_one(user=user)


if __name__ == "__main__":
    run()
